package com.xzz.finger;


/**
 * @author: hhz
 * @create: 2022-02-17 14:28
 * 剑指 Offer 07. 重建二叉树
 * 输入某二叉树的前序遍历和中序遍历的结果，请构建该二叉树并返回其根节点。
 **/
public class BuildTree {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public static void main(String[] args) {
        System.out.println(buildTree(new int[]{3, 9, 20, 15, 7}, new int[]{9, 3, 15, 20, 7}));
    }

    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
    }

    public static TreeNode build(int[] preorder,int preStart,int preEnd, int[] inorder,int inStart,int inEnd) {
        if(preStart>preEnd){
            return null;
        }
        TreeNode treeNode = new TreeNode(preorder[preStart]);
        //计算根节点在 中序遍历中的index
        int index = -1;
        for (int i = inStart;i<=inEnd;i++){
            if(inorder[i] == preorder[preStart]){
                index = i;
                break;
            }
        }
        int leftSize = index - inStart;
        treeNode.left = build(preorder,preStart+1,preStart+leftSize,inorder,inStart,index-1);
        treeNode.right = build(preorder,preStart+leftSize+1,preEnd,inorder,index+1,inEnd);
        return treeNode;
    }
}
